<?php
// 社区分享
class ShareController extends AppController {

    public $layout = 'comm';

    function beforeFilter() {
        parent::beforeFilter();
        if($this->checkLogin()){ 
            $this->user = $this->getUser();  
            $this->set('userInfo',$this->user); 
        }  
        $this->set('nav','share');  
    }

    function index($cid = null){
        $params = $this->request->query;
        //区域ID
        $cid = $this->rm_end_html($cid);
        $params = $this->get_params($cid); 
        $cid = $params[0]; 
        $this->loadModel('Share');  
        $this->loadModel('District'); 
        $this->loadModel('User'); 
        $this->loadModel('Hospital'); 
        $this->loadModel('Picture');     
        $conditions =$coments = array();
        $orderby=[];
        if(!empty($cid) && $cid>0){ 
            $conditions['tag2'] = intval($cid); 
        } 
         
        $seletCss="";
        if(isset($params[1]) &&  !empty($params[1])){
            $conditions['tag'] = intval($params[1]);
            $seletCss=intval($params[1]);
        }

        $seachTitle="";
        if(isset($params[2]) && !empty($params[2])){ 
            $conditions["OR"]['title like'] = '%'.$params[2].'%';
            $conditions["OR"]['content like'] = '%'.$params[2].'%'; 
            $seachTitle=$params[2];
        }
        $orderby['sort']="desc"; 
        $orderby['update_time']="desc"; 
        $conditions['status'] = 1;
        $conditions['type']=0;
        $dataList = array(); 
        $dataList = $this->Share->find('all',array(
            'conditions' => $conditions, 
            'limit' => 10,
            'order' => $orderby,
            )
        ); 
  
        $picTopic=Configure::read('PIC_TOPIC');
        $this->loadModel('Agree'); 
        $agreeTopic=Configure::read('AGREE_TOPIC');
        $userId=intval($this->user['id']);
        $districtList = $this->District->find('all',array('order'=>array('sort'=>'desc','id'=>'asc'),'fields'=>array('id','country')));  
        if(!empty($dataList)){
            foreach ($dataList as $key => $value) { 
                $dataList[$key]['Share']['hospital']="无";
                if(intval($value['Share']['hospital_id'])>0){ 
                    $info = $this->Hospital->findById(intval($value['Share']['hospital_id']));
                    if(isset($info['Hospital']['id']))
                        $dataList[$key]['Share']['hospital']=$info['Hospital']['cn_name'];
                } 
                $agCount = $this->Agree->find('count',array('conditions'=>array('uid'=>$userId,'obj_id'=>$value['Share']['id'],'obj_type'=>$agreeTopic['分享'])));
                $dataList[$key]['Share']['myagree']=$agCount; 
                 $picData = $this->Picture->find('all',array('conditions'=>array('obj_type'=>$picTopic['分享'],'obj_id'=>intval($value['Share']['id'])),'fields'=>array('thumb'))); 
                 $dataList[$key]['Share']['images']=$picData; 
                 $userInfo=$this->User->findById(intval($value['Share']['uid'])); 
                 $dataList[$key]['Share']['username']=isset($userInfo['User']['nick_name'])?$userInfo['User']['nick_name']:"保密";
                if(empty($value['Share']['description']) && !empty($value['Share']['content'])){
                    $value['Share']['description']=Ivf::getSubstr(strip_tags($value['Share']['content']),0,200); 
                } 
                $dataList[$key]['Share']['description']= Ivf::getLittleText($value['Share']['description'],Ivf::getOSInfo(strtolower($_SERVER['HTTP_USER_AGENT'])));     
                $dataList[$key]['Share']['avatar']=isset($userInfo['User']['avatar'])?$userInfo['User']['avatar']:'';
            }
            foreach ($dataList as $key => $value) {              //从内容中取三张图片方法
            $html = $value['Share']['content'];
            preg_match_all('/<img\s+src=".*?"/', $html, $matches);
             $dataList[$key]['Share']['images'] = $matches;
            }
        }  

        $conditions=$orderby=[];
        //总排行
        $orderby['browse_num']="desc";  
        $conditions['status'] = 1;
        $conditions['type']=0;
        $topList = array(); 
        $topList = $this->Share->find('all',array(
            'conditions' => $conditions, 
            'limit' => 5,
            'order' => $orderby,
            )
        );
        if(!empty($topList)){
            foreach ($topList as $key => $value) { 
                $topList[$key]['Share']['avatar']='/images/common/grey.gif';
                if($value['Share']['uid'] > 0){
                    $userInfo = $this->User->findById($value['Share']['uid']);    
                    $topList[$key]['Share']['avatar']=$userInfo['User']['avatar'];
                }
            }
        } 

        //周排行
        $startTime=date("Y-m-d",time());
        $conditions['create_time >= '] =date('Y-m-d',strtotime("$startTime - 7 days"))." 00:00:00";    
        $weekList = array();  
        $weekList = $this->Share->find('all',array(
            'conditions' => $conditions, 
            'limit' => 5,
            'order' => $orderby,
            )
        );

        if(!empty($weekList)){
            foreach ($weekList as $key => $value) { 
                $weekList[$key]['Share']['avatar']='/images/common/grey.gif';
                if($value['Share']['uid'] > 0){
                    $userList = $this->User->findById($value['Share']['uid']);    
                    $weekList[$key]['Share']['avatar']=isset($userList['User']['avatar'])?$userList['User']['avatar']:'';
                }
            }
        }  

        $this->loadModel('Keyword');  
        $share_tags=Configure::read('SHARE_TAG');
        $keyTopic=Configure::read('KEYWORDS_TYPE');
        $keysInfo = $this->Keyword->find('first',array('conditions'=>array('key'=>$keyTopic['分享列表']),'order'=>array('id'=>'desc'))); 
        if(!empty($keysInfo) && !empty($seletCss))
            $keysInfo['Keyword']['meta_title']=isset($share_tags[$seletCss])?$share_tags[$seletCss]."_".$keysInfo['Keyword']['meta_title']:$keysInfo['Keyword']['meta_title'];
        $this->set('keysInfo',$keysInfo);
        $this->set('seletCss',$seletCss);
        $this->set('dataList',$dataList);
        $this->set('weekList',$weekList);
        $this->set('topList',$topList);
        $this->set('districtList',$districtList); 
        $this->set('share_tags',$share_tags);
        $this->set('share_tags2',Configure::read('SHARE_TAG_TWO'));
        $this->set('cid',intval($cid)); 
        $this->set('seachTitle',$seachTitle); 
    }

    function info($id = 0){
        if(empty($id)){
            $this->redirect('/');
        }
        $id = $this->rm_end_html($id);
        $this->loadModel('Share');     
        $this->loadModel('User');    
        $this->loadModel('District');     
        $this->loadModel('Picture');   
        $this->loadModel('Comment');      
        $this->loadModel('Agree'); 
        $userId=intval($this->user['id']);   
        $agreeTopic=Configure::read('AGREE_TOPIC');
        $commentTopic=Configure::read('COMMENT_TOPIC');
    	$info = $this->Share->find('first',array('conditions'=>array('status'=>1,'type'=>0,'id'=>$id)));

        // $fatie = $this->Share->findById("all",array('conditions'=>array('id'=>$id,)));
        $num=$this->Share->find('count',array('conditions' => array('uid'=>$info['Share']['uid'])));
        if(empty($info)){
            //处理错误跳转
            die("非法请求");
        }  
        $info['Share']['username']="试管无忧";
        $picTopic=Configure::read('PIC_TOPIC');
        if($info['Share']['uid']>0){
            $userInfo=$this->User->findById(intval($info['Share']['uid']));
            $cyInfo=$this->District->findById(intval($info['Share']['city_id']));
            $info['Share']['username']=isset($userInfo['User']['nick_name'])?$userInfo['User']['nick_name']:"保密";
            $info['Share']['avatar']=isset($userInfo['User']['avatar'])?$userInfo['User']['avatar']:'';
            $info['Share']['city']=isset($cyInfo['District']['country'])?$cyInfo['District']['country']:"保密";
             $picData = $this->Picture->find('all',array('conditions'=>array('obj_type'=>$picTopic['分享'],'obj_id'=>intval($info['Share']['id'])),'fields'=>array('thumb'))); 
             $info['Share']['images']=$picData; 
        } 
        $comments = $this->Comment->find('all',array('conditions'=>array('topic_type'=>$commentTopic['分享'],'parent_id'=>0,'topic_id'=>$id),'order'=>array('is_top'=>'desc','sort'=>'desc','comment_time' => 'desc'),'limit' => 5));
        if(!empty($comments)){
            foreach ($comments as $key => $value) { 
                $userInfo = $this->User->findById($value['Comment']['uid']);    
                $childCmt = $this->Comment->find('all',array('conditions'=>array('topic_type'=>$commentTopic['分享'],'parent_id'=>$value['Comment']['id']),'order'=>array('is_top'=>'desc','sort'=>'desc','comment_time' => 'asc'),'fields'=>array('id','comment_time','uid','reply_id','content')));
                $childAttr=[];
                if(!empty($childCmt)){
                    foreach ($childCmt as $kk => $vv) {
                        $uInfo = $this->User->findById($vv['Comment']['uid']); 
                        if(!empty($uInfo)){ 
                            $vv['Comment']['replayName']=isset($uInfo['User']['nick_name'])?$uInfo['User']['nick_name']:$uInfo['User']['mobile'];
                            if($vv['Comment']['reply_id']>0 && $vv['Comment']['reply_id']!=$value['Comment']['id']){
                                $cInfo = $this->Comment->findById($vv['Comment']['reply_id']); 
                                if(empty($cInfo)) continue; 
                                $uInfo = $this->User->findById($cInfo['Comment']['uid']); 
                                $vv['Comment']['replayName']=$vv['Comment']['replayName']." <em>回复</em> ".(isset($uInfo['User']['nick_name'])?$uInfo['User']['nick_name']:$uInfo['User']['mobile']);

                            }
                            $childAttr[]=$vv['Comment'];
                        } 
                    }
                }
                $comments[$key]['Comment']['username']=isset($userInfo['User']['nick_name'])?$userInfo['User']['nick_name']:"保密";
                $comments[$key]['Comment']['avatar']=$userInfo['User']['avatar'];
                $comments[$key]['Comment']['childCmt']=$childAttr;
            }
        } 

        $conditions=$orderby=[];
        //总排行
        $orderby['browse_num']="desc";  
        $conditions['status'] = 1;
        $conditions['type']=0;
        $topList = array(); 
        $topList = $this->Share->find('all',array(
            'conditions' => $conditions, 
            'limit' => 5,
            'order' => $orderby,
            )
        );
        if(!empty($topList)){
            foreach ($topList as $key => $value) { 
                $topList[$key]['Share']['avatar']='/images/common/grey.gif';
                if($value['Share']['uid'] > 0){
                    $userInfo = $this->User->findById($value['Share']['uid']);    
                    $topList[$key]['Share']['avatar']=$userInfo['User']['avatar'];
                }
            }
        } 

        //周排行
        $startTime=date("Y-m-d",time());
        $conditions['create_time >= '] =date('Y-m-d',strtotime("$startTime - 7 days"))." 00:00:00";    
        $weekList = array();  
        $weekList = $this->Share->find('all',array(
            'conditions' => $conditions, 
            'limit' => 5,
            'order' => $orderby,
            )
        );

        if(!empty($weekList)){
            foreach ($weekList as $key => $value) { 
                $weekList[$key]['Share']['avatar']='/images/common/grey.gif';
                if($value['Share']['uid'] > 0){
                    $userList = $this->User->findById($value['Share']['uid']);    
                    $weekList[$key]['Share']['avatar']=isset($userList['User']['avatar'])?$userList['User']['avatar']:'';
                }
            }
        }  
        $agCount = $this->Agree->find('count',array('conditions'=>array('uid'=>$userId,'obj_id'=>$info['Share']['id'],'obj_type'=>$agreeTopic['分享'])));
        $info['Share']['myagree']=$agCount;
        //浏览数+1 
        $this->Share->updateAll(array('Share.browse_num'=>'`Share`.`browse_num`+1'), array('Share.id'=>$id)); 
        $keysInfo=[];
        $keysInfo['Keyword']['meta_title']=$info['Share']['title'].'_泰国试管婴儿经验分享 - 试管邦社区'; 
        $keysInfo['Keyword']['meta_keywords']=$info['Share']['title'].",泰国试管婴儿经验分享"; 
        $keysInfo['Keyword']['meta_description']=Ivf::getSubstr(strip_tags($info['Share']['description']),0,200,''); 
        $this->set('keysInfo',$keysInfo); 
    	$this->set('info',$info);  
        $this->set('share_tags',Configure::read('SHARE_TAG'));
        $this->set('comments',$comments); 
        $this->set('weekList',$weekList); 
        $this->set('topList',$topList); 
        $this->set('num',$num);
    }

    function replay(){ 
        // 发表评论   
        $this->checkLogin(1);     
        $params = $this->request->data;
        $commentTopic=Configure::read('COMMENT_TOPIC');
        $this->loadModel('Share');   
        $this->loadModel('Comment');  
        if($this->request->is('post')){ 
            if($params['cid'] <=0){
                $this->ajaxReturn(4008, '非法请求!');  
            }
            if(empty($params['content'])){
                $this->ajaxReturn(4007, '内容不能为空!');  
            }

            if(isset($params['dosubmit']) && $params['dosubmit']==1){
                if(empty($params['u_code']))
                    $this->ajaxReturn(4003, '验证码不能为空!');   
                App::uses('ImageCaptcha','Lib');
                $ImageCaptcha = new ImageCaptcha();
                $captcha=$ImageCaptcha->check_captcha_code($params['u_code']);
                if($captcha['status']=="fail") $this->ajaxReturn(4005, $captcha['msg']);   
            } 

            $info = $this->Share->find('first',array('conditions'=>array('status'=>1,'type'=>0,'id'=>intval($params['cid']))));
            if(empty($info))
                $this->ajaxReturn(4006, '非法提交!');   

            $cinfo = $this->Comment->find('first',array('conditions'=>array('topic_type'=>$commentTopic['分享'],'topic_id'=>$info['Share']['id'],'reply_id'=>0,'uid'=>$this->user['id'])));
            if(!empty($cinfo))
                $this->ajaxReturn(4009, '不能重复评论!');  
            //添加评论
            $data=[];
            $data['topic_type']=$commentTopic['分享'];
            $data['topic_id']=$info['Share']['id'];
            $data['uid'] = $this->user['id']; 
            $data['sort'] = 1100; 
            $data['content'] = $params['content'];   
            $data['comment_time']=date("Y-m-d H:i:s",time());
            $data['create_time']=date("Y-m-d H:i:s",time());
            $this->Comment->save($data);
            $data=[];
            $data['id']=$info['Share']['id'];
            if($info['Share']['is_replay']==0){
                $data['is_replay']=1;
            }
            $data['comment_num']=$info['Share']['comment_num']+1;
            $this->Share->save($data);
            $this->ajaxReturn(200, '发表成功！');   
        }
        $this->ajaxReturn(4007, '异常提交！');    
    } 


    function replay_answer(){ 
        // 发表评论   
        $this->checkLogin(1);  
        $params = $this->request->data;
        $commentTopic=Configure::read('COMMENT_TOPIC');
        $this->loadModel('Share');   
        $this->loadModel('Comment');  
        if($this->request->is('post') && $params['dosubmit']==1){ 
            if($params['cid'] <=0 || $params['reply_id'] <=0){
                $this->ajaxReturn(4008, '请选择回复评论!');  
            }
            if(empty($params['content'])){
                $this->ajaxReturn(4007, '内容不能为空!');  
            }

            $info = $this->Share->find('first',array('conditions'=>array('status'=>1,'type'=>0,'id'=>intval($params['cid']))));
            if(empty($info))
                $this->ajaxReturn(4006, '非法提交!');  

            $rpinfo = $this->Comment->findById(intval($params['reply_id']));

            if(empty($rpinfo))
                $this->ajaxReturn(4007, '非法提交!');   

            if($rpinfo['Comment']['uid']==$this->user['id']){
                $this->ajaxReturn(4008, '不能回复自己!');  
            }  
            //添加评论
            $data=[];
            if($rpinfo['Comment']['parent_id']==0)
                $data['parent_id']=$rpinfo['Comment']['id'];
            else
                $data['parent_id']=$rpinfo['Comment']['parent_id']; 
            $data['topic_type']=$commentTopic['分享'];
            $data['topic_id']=$info['Share']['id'];
            $data['reply_id']=intval($params['reply_id']);
            $data['uid'] = $this->user['id']; 
            $data['sort'] = 1100; 
            $data['content'] = $params['content'];   
            $data['comment_time']=date("Y-m-d H:i:s",time());
            $data['create_time']=date("Y-m-d H:i:s",time());
            $this->Comment->save($data);
            $data=[];
            $data['id']=$info['Share']['id'];
            if($info['Share']['is_replay']==0){
                $data['is_replay']=1;
            }
            $data['comment_num']=$info['Share']['comment_num']+1;
            $this->Share->save($data);
            $this->ajaxReturn(200, '发表成功！');   
        }
        $this->ajaxReturn(4007, '异常提交！');    
    }  
}